package com.example.demo.zip;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
import org.apache.commons.compress.archivers.sevenz.SevenZOutputFile;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.StopWatch;

import java.io.*;

/**
 * 文件描述 7z解压缩工具类
 *
 * @author
 * @date
 */
@Slf4j(topic = "SevenZipUtil")
public class SevenZipUtil {


    /**
     * 7z文件压缩
     *
     * @param inputFile  待压缩文件夹/文件名
     * @param outputFile 生成的压缩包名字
     */
    public static void compress7z(String inputFile, String outputFile) {
        log.info("开始7z压缩本地路径{}的相关日志到{}压缩文件中", inputFile, outputFile);
        StopWatch watch = new StopWatch();
        watch.start("7z压缩");
        SevenZOutputFile outArchive = null;
        try {
            File input = new File(inputFile);
            if (!input.exists()) {
                throw new RuntimeException(input.getPath() + "待压缩文件不存在");
            }
            File output = new File(outputFile);
            outArchive = new SevenZOutputFile(output);
            // 递归压缩
            compress(outArchive, input, null);
        } catch (Exception e) {
            log.error("7z文件压缩出现异常源路径{},目标路径{}", inputFile, outputFile, e);
            throw new RuntimeException("7z文件压缩出现异常");
        } finally {
            // 关闭
            closeSevenZOutputFile(outArchive);
        }

        watch.stop();
        log.info("结束7z压缩本地路径{}的相关日志到{}压缩文件中,耗时{}ms", inputFile, outputFile, watch.getTotalTimeMillis());
    }

    /**
     * 关闭SevenZOutputFile
     *
     * @param outArchive
     */
    public static void closeSevenZOutputFile(SevenZOutputFile outArchive) {
        try {
            if (null != outArchive) {
                outArchive.close();
            }
        } catch (Exception e) {
            log.error("关闭SevenZOutputFile出现异常", e);
            throw new RuntimeException("关闭SevenZOutputFile出错");
        }
    }

    /**
     * 递归压缩
     *
     * @param outArchive
     * @param input
     * @param name
     * @throws IOException
     * @throws FileNotFoundException
     */
    public static void compress(SevenZOutputFile outArchive, File input, String name) throws IOException, FileNotFoundException {
        SevenZArchiveEntry entry = null;
        // 如果路径为目录（文件夹）
        if (input.isDirectory()) {
            // 取出文件夹中的文件（或子文件夹）
            File[] fileList = input.listFiles();

            if (fileList.length == 0) {
                // 如果文件夹为空，则只需在目的地.7z文件中写入一个目录进入,即在7z中创建一个文件夹
                entry = outArchive.createArchiveEntry(input, name + File.separator);
                outArchive.putArchiveEntry(entry);
                outArchive.closeArchiveEntry();
            } else {
                // 如果文件夹不为空，则递归调用compress，文件夹中的每一个文件（或文件夹）进行压缩
                for (int i = 0; i < fileList.length; i++) {
                    String curFileName = fileList[i].getName();
                    // 压缩文件去除根目录
                    compress(outArchive, fileList[i], StringUtils.isEmpty(name) ? curFileName : (name + File.separator + curFileName));
                }
            }
        } else {
            // 如果不是目录（文件夹），即为文件，则先写入目录进入点，之后将文件写入7z文件中
            FileInputStream fos = new FileInputStream(input);
            BufferedInputStream bis = new BufferedInputStream(fos);
            entry = outArchive.createArchiveEntry(input, name);
            outArchive.putArchiveEntry(entry);
            int len = -1;
            // 将源文件写入到7z文件中
            byte[] buf = new byte[1024];
            while ((len = bis.read(buf)) != -1) {
                outArchive.write(buf, 0, len);
            }
            bis.close();
            fos.close();
            outArchive.closeArchiveEntry();
        }
    }

    /**
     * 7z文件解压
     *
     * @param inputFile   待解压文件名
     * @param destDirPath 解压路径
     */
    public static void unCompress7z(String inputFile, String destDirPath) throws Exception {
        StopWatch watch = new StopWatch();
        watch.start("7z解缩");
        // 获取当前压缩文件
        File srcFile = new File(inputFile);
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new Exception(srcFile.getPath() + "所指文件不存在");
        }
        // 开始解压
        SevenZFile zIn = new SevenZFile(srcFile);
        SevenZArchiveEntry entry = null;
        File file = null;
        while ((entry = zIn.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                file = new File(destDirPath, entry.getName());
                if (!file.exists()) {
                    // 创建此文件的上级目录
                    new File(file.getParent()).mkdirs();
                }
                OutputStream out = new FileOutputStream(file);
                BufferedOutputStream bos = new BufferedOutputStream(out);
                int len = -1;
                byte[] buf = new byte[1024];
                while ((len = zIn.read(buf)) != -1) {
                    bos.write(buf, 0, len);
                }
                // 关流顺序，先打开的后关闭
                bos.close();
                out.close();
            }
        }

        watch.stop();
        log.info("结束7z解压,耗时{}ms", watch.getTotalTimeMillis());

    }

}
